package yxt.push.org.jivesoftware.smackx;

import yxt.push.org.jivesoftware.smack.ConnectionYxt;
import yxt.push.org.jivesoftware.smack.PacketCollectorYxt;
import yxt.push.org.jivesoftware.smack.SmackConfigurationYxt;
import yxt.push.org.jivesoftware.smack.XMPPExceptionYxt;
import yxt.push.org.jivesoftware.smack.filter.PacketIDFilterYxt;
import yxt.push.org.jivesoftware.smack.packet.IQYxt;
import yxt.push.org.jivesoftware.smackx.packet.SharedGroupsInfo;

import java.util.List;

/**
 * A SharedGroupManager provides services for discovering the shared groups where a user belongs.<p>
 *
 * Important note: This functionality is not part of the XMPP spec and it will only work
 * with Wildfire.
 *
 * @author Gaston Dombiak
 */
public class SharedGroupManager {

    /**
     * Returns the collection that will contain the name of the shared groups where the user
     * logged in with the specified session belongs.
     *
     * @param connection connection to use to get the user's shared groups.
     * @return collection with the shared groups' name of the logged user.
     */
    public static List getSharedGroups(ConnectionYxt connection) throws XMPPExceptionYxt {
        // Discover the shared groups of the logged user
        SharedGroupsInfo info = new SharedGroupsInfo();
        info.setType(IQYxt.Type.GET);

        // Create a packet collector to listen for a response.
        PacketCollectorYxt collector =
            connection.createPacketCollector(new PacketIDFilterYxt(info.getPacketID()));

        connection.sendPacket(info);

        // Wait up to 5 seconds for a result.
        IQYxt result = (IQYxt) collector.nextResult(SmackConfigurationYxt.getPacketReplyTimeout());
        // Stop queuing results
        collector.cancel();
        if (result == null) {
            throw new XMPPExceptionYxt("No response from the server.");
        }
        if (result.getType() == IQYxt.Type.ERROR) {
            throw new XMPPExceptionYxt(result.getError());
        }
        return ((SharedGroupsInfo) result).getGroups();
    }
}
